import { PageHeaderWrapper } from '@ant-design/pro-layout';
import type { ProColumns } from '@ant-design/pro-components';
import { ProTable } from '@ant-design/pro-components';
import { Progress, Tooltip } from 'antd';
import CreateTask from './components/CreateTask';
import type { BatchTaskTableItem } from './data.d';
import { TaskType, TaskStatus } from './data.d';
import { queryBatchTasks } from './service';
import TaskDetailList from './components/TaskDetailList';
import { useModel } from 'umi';
import { Auths } from '@/utils/types.d';

const handleTaskDetail = (item: BatchTaskTableItem) => {
  if (!item || !item.result || !item.result.code) return '等待中';
  switch (item.result.code) {
    case TaskStatus.SUCCESS:
      return '全部成功';
    case TaskStatus.PARTIAL_SUCCESS:
      return `${item?.success}条记录添加成功，请点击详情查看`;
    case '添加列表中存在重复路段名':
    case '添加列表中存在重复的地磁编号':
      return item.result.detail;
    case '添加记录条数单次不能超过5000':
      return '添加记录条数单次不能大于5000，请分次添加';
    case TaskStatus.PROCESSING:
      return '正在处理中';
    case '未知错误':
      return item.result.detail;
    default:
      return item.result.code;
  }
};

export default () => {
  const { initialState } = useModel('@@initialState');
  const currUser = initialState?.currentUser;
  const auths = currUser?.auth ? new Set(currUser.auth.batchTask || []) : new Set();
  const ifPkSpotImp = auths.has(Auths.PKSPOT_IMP);
  const ifPkLotImp = auths.has(Auths.PKLOT_IMP);
  const ifSensorBind = auths.has(Auths.SENSOR_BIND);
  const columns: ProColumns<BatchTaskTableItem>[] = [
    {
      title: 'id',
      hideInSearch: true,
      hideInTable: true,
      dataIndex: '_id',
    },
    {
      title: '任务类型',
      width: 150,
      dataIndex: 'type',
      hideInSearch: true,
      valueEnum: {
        [TaskType.CREATE_PKLOT]: '批量创建路段',
        [TaskType.CREATE_PKSPOT]: '批量创建泊位',
        [TaskType.BIND_SENSOR]: '批量绑定地磁',
        [TaskType.CREATE_PATROL]: '批量创建巡检设备',
        [TaskType.CREATE_SENSOR]: '批量创建地磁设备',
        [TaskType.IMPORT_ORDER]: '批量导入欠费订单',
        [TaskType.OUT_CAR]: '批量驶出订单',
      },
    },
    {
      title: '创建时间',
      width: 180,
      align: 'center',
      dataIndex: 'createTime',
      valueType: 'dateTime',
      hideInSearch: true,
    },
    {
      title: '任务状态',
      width: 110,
      dataIndex: 'status',
      align: 'center',
      valueEnum: {
        [TaskStatus.FILE_LOADING]: { text: '文件上传中', status: 'Processing' },
        [TaskStatus.ERROR]: { text: '失败', status: 'Error' },
        [TaskStatus.SUCCESS]: { text: '成功', status: 'Success' },
        [TaskStatus.PARTIAL_SUCCESS]: { text: '部分成功', status: 'Success' },
        [TaskStatus.PROCESSING]: { text: '执行中', status: 'Processing' },
        pending: { text: '队列中', status: 'Default' },
      },
      hideInSearch: true,
    },
    {
      title: '成功率',
      width: 150,
      align: 'center',
      dataIndex: 'success',
      hideInSearch: true,
      render: (_, record) => (
        <div style={{ width: 120, margin: '0 auto' }}>
          <Progress percent={Math.floor((record.success / record.total) * 100)} size="small" />
        </div>
      ),
    },
    {
      title: '结束时间',
      width: 180,
      dataIndex: 'finishedTime',
      align: 'center',
      valueType: 'dateTime',
      hideInSearch: true,
    },
    {
      title: '任务描述',
      width: 300,
      dataIndex: 'result',
      hideInSearch: true,
      render: (_, record) => {
        const msg = handleTaskDetail(record);
        return (
          <Tooltip title={msg}>
            <div
              style={{
                width: '100%',
                overflow: 'hidden',
                textOverflow: 'ellipsis',
                whiteSpace: 'nowrap',
                wordBreak: 'keep-all',
                // color,
              }}
            >
              {msg}
            </div>
          </Tooltip>
        );
      },
    },
    {
      title: '操作',
      width: 100,
      fixed: 'right',
      align: 'center',
      valueType: 'option',
      render: (_, record) => [
        <TaskDetailList key={record._id} id={record._id} taskType={record.type} />,
      ],
    },
  ];
  return (
    <PageHeaderWrapper
      header={{
        title: '',
        subTitle:
          '此处您可以批量给泊位绑定地磁、批量添加路段、批量创建泊位、批量添加巡检设备和地磁设备',
        breadcrumb: {
          routes: [
            { path: '/', breadcrumbName: '首页' },
            { path: '/batch-tasks', breadcrumbName: '批量任务' },
          ],
        },
      }}
    >
      <ProTable<BatchTaskTableItem>
        columns={columns}
        search={false}
        rowKey="id"
        polling={60000}
        columnEmptyText="暂无数据"
        scroll={{ x: true }}
        style={{ whiteSpace: 'nowrap' }}
        pagination={{
          showSizeChanger: true,
          showQuickJumper: true,
          defaultPageSize: 10,
          size: 'default',
        }}
        debounceTime={300}
        request={async (param, sort) => {
          const res = await queryBatchTasks(param, sort);
          return res;
        }}
        toolBarRender={(action) => [
          (ifPkSpotImp || ifPkLotImp || ifSensorBind) && (
            <CreateTask func={() => action?.reload()} />
          ),
        ]}
      />
    </PageHeaderWrapper>
  );
};
